﻿#region Copyright (c) 2007-2010 Mikko Salmi, Contributors
/*
 *
 * Copyright (c) 2007-2010 Mikko Salmi, Contributors
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
 * 
*/
#endregion // Copyright

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.WebPartPages;

namespace CodePlex.WebParts
{
    [XmlRoot(Namespace = "CodePlex.WebParts")]
    [Guid("1D739F65-0FA7-4c7b-8BE9-208E2309CC74")]
    public class VideoPlaylistWebPart : AdvancedWebPart
    {
        private const string libraryNameDefault = "Video";
        string libraryName = libraryNameDefault;

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable,
        WebDisplayName("Library Name"),
        WebDescription("The name of the library containing video files for video player web part."),
        SPWebCategoryName("Video Player")]
        public string LibraryName
        {
            get
            {
                return libraryName;
            }
            set
            {
                libraryName = value;
            }
        }

        private const string thumbnailLibraryNameDefault = "Video Thumbnails";
        string thumbnailLibraryName = thumbnailLibraryNameDefault;

        [Personalizable(PersonalizationScope.Shared),
          WebBrowsable,
          WebDisplayName("Thumbnail Library Name"),
          WebDescription("The name of the library containing video thumbnails for the video files. To attach an image with a video, the name of the thumbnail file should be same as the video file name."),
          SPWebCategoryName("Video Player")]
        public string ThumbnailLibraryName
        {
            get
            {
                return thumbnailLibraryName;
            }
            set
            {
                thumbnailLibraryName = value;
            }
        }

        PlaceHolder phPlaylist;

        LiteralControl litPlayScript;

        public VideoPlaylistWebPart()
        {
        }

        protected override void CreateChildControls()
        {
            // Add link to style sheet.
            string styleSheetUrl = SPContext.Current.Web.Url + @"/_layouts/CodePlex/VideoPlaylistWebPart/VideoPlaylist.css";
            WebPartTools.CreateStyleSheetLink(this.Page, styleSheetUrl);

            base.CreateChildControls();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            litPlayScript = new LiteralControl();
            phPlaylist = new PlaceHolder();
                        
            SPWeb web = SPContext.Current.Web;

            try
            {
                if (web.Lists[libraryName] == null)
                {

                }
                else if (web.Lists[libraryName].Items.Count > 0)
                {
                    string playerNumber = getPlayerNumber();

                    litPlayScript.Text =
                        "<script type=\"text/javascript\"> " + Environment.NewLine +
                        "   function Play" + playerNumber + "(playlistIndex) " + Environment.NewLine +
                        "   { " + Environment.NewLine +
                        "       player_" + playerNumber + "._onClickGalleryItem(playlistIndex); " + Environment.NewLine +
                        "   } " + Environment.NewLine +
                        "</script>" + Environment.NewLine;

                    phPlaylist.Controls.Add(new LiteralControl("<br/>"));

                    int i = 0;
                    foreach (SPListItem video in web.Lists[libraryName].Items)
                    {
                        phPlaylist.Controls.Add(new LiteralControl("&nbsp;" + "<div class='playlistDiv' onClick='javascript: Play" + playerNumber + "(" + i + ");'>"));

                        bool thumbAdded = false;

                        foreach (SPListItem thumb in web.Lists[thumbnailLibraryName].Items)
                        {
                            bool isCorrectThumb = false;

                            if (thumb["Name"].ToString().Split('.')[0] == video["Name"].ToString().Split('.')[0])
                                isCorrectThumb = true;

                            if (isCorrectThumb)
                            {
                                phPlaylist.Controls.Add(new LiteralControl("<div class='playlistImage'><img name='" + thumb["Name"] + "' src='" + thumb["ows_EncodedAbsUrl"] + "' /></div>"));

                                if (!string.IsNullOrEmpty((string)video["Title"]))
                                {
                                    phPlaylist.Controls.Add(new LiteralControl("<div class='playlistVideoName'>" + video["Title"] + "</div>"));
                                }
                                else
                                {
                                    phPlaylist.Controls.Add(new LiteralControl("<div class='playlistVideoName'>" + video["Name"] + "</div>"));
                                }

                                phPlaylist.Controls.Add(new LiteralControl("<div class='playlistDescription'>" + thumb["Description"] + "</div>"));

                                thumbAdded = true;

                                break;
                            }
                        }

                        if (!thumbAdded)
                        {
                            phPlaylist.Controls.Add(new LiteralControl("<div class='playlistImage'><img name='emptyThumb' src='" + SPContext.Current.Web.Url + @"/_layouts/CodePlex/VideoPlaylistWebPart/NoThumb.png" + "' /></div>"));

                            if (!string.IsNullOrEmpty((string)video["Title"]))
                            {
                                phPlaylist.Controls.Add(new LiteralControl("<div class='playlistVideoName'>" + video["Title"] + "</div>"));
                            }
                            else
                            {
                                phPlaylist.Controls.Add(new LiteralControl("<div class='playlistVideoName'>" + video["Name"] + "</div>"));
                            }

                            phPlaylist.Controls.Add(new LiteralControl("<div class='playlistDescription'></div>"));
                        }

                        phPlaylist.Controls.Add(new LiteralControl("</div><br />"));

                        i++;
                    }
                }
            }
            catch
            {
                phPlaylist.Controls.Add(new LiteralControl("<br/>"));
                phPlaylist.Controls.Add(new LiteralControl("Error accessing video files."));
            }
            
            this.Controls.Add(litPlayScript);
            this.Controls.Add(phPlaylist);
        }

        protected string getPlayerNumber()
        {
            int i = 0;
            foreach (System.Web.UI.WebControls.WebParts.WebPart part in this.WebPartManager.WebParts)
            {
                if (part.GetType() == typeof(VideoPlaylistWebPart))
                {
                    if (part.ID == this.ID)
                    {
                        break;
                    }

                    i++;
                }
            }

            return i.ToString();
        }

        private string createVideoJs()
        {
            SPWeb web = SPContext.Current.Web;

            string videoJs = string.Empty;

            try
            {
                if (web.Lists[libraryName].Items.Count == 0)
                    return string.Empty;

                videoJs = "'this._playlist=['+";

                int i = 1;

                foreach (SPListItem video in web.Lists[libraryName].Items)
                {
                    videoJs +=
                                "'{\"mediaSource\":\"" + video["ows_EncodedAbsUrl"] + "\",'+ " +
                                "'\"placeholderSource\":\"\",'+ " +
                                "'\"chapters\":'+" +
                                "'['+" +
                                "']}'+";

                    if (i < web.Lists[libraryName].ItemCount)
                    {
                        videoJs += "',' +";
                    }

                    i++;
                }
            }
            catch
            {
                // libraryName was not found.
                videoJs = string.Empty;
            }

            videoJs += "'];'";

            //return videoJs;
            return videoJs;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }             
    }
}